from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

from entities import Contact

class MainPage(webapp.RequestHandler):
    
    
    def get(self):
        user = users.get_current_user()

        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return
        else:
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'

        contacts = Contact.all()
        contacts.filter("owner =", user)

        template_values = {
            'contacts': contacts,
            'name': user.nickname(),
            'url': url,
            'url_linktext': url_linktext,
        }

        import os
        
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))


class AddContact(webapp.RequestHandler):
    def post(self):
        user = users.get_current_user()
        
        if user:        
            name = self.request.get('name')
            email = self.request.get('email')
            
            if name and email:
                contact = Contact(owner=user, name=name, email=email)
                contact.put()
            
        self.redirect('/')
        
application = webapp.WSGIApplication([('/', MainPage), ('/addContact', AddContact)], debug=True)


def main():
    run_wsgi_app(application)


if __name__ == "__main__":
    main()





